package com.sopaths.crawler.task.handler;

import javax.inject.Inject;
import javax.inject.Named;

import org.apache.log4j.Logger;

import com.sopaths.contract.crawler.CrawlerTaskType;
import com.sopaths.crawler.tasks.CrawlerTask;
import com.sopaths.crawler.tasks.SummaryCrawlerTask;
import com.sopaths.crawler.tasks.SummaryTotalPageCrawlerTask;
import com.sopaths.crawler.thread.CrawlerTaskExecutor;

@Named
public class SummaryTotalPageCrawlerTaskResultHandler implements CrawlerTaskResultHandler {

	private Logger logger = Logger.getLogger(SummaryTotalPageCrawlerTaskResultHandler.class);

	@Inject
	@Named("summaryCrawlerTaskExecutor")
	private CrawlerTaskExecutor taskExecutor;

	@Override
	public void handle(CrawlerTask<?> task) {
		try {
			SummaryTotalPageCrawlerTask innerTask = (SummaryTotalPageCrawlerTask) task;
			int totalPage = innerTask.getResult();
			for (int i = 1; i <= totalPage; i++) {
				SummaryCrawlerTask summaryTask = new SummaryCrawlerTask();
				summaryTask.setSource(innerTask.getSource());
				summaryTask.setType(CrawlerTaskType.SummaryCrawlerTask);
				summaryTask.setCity(innerTask.getCity());
				summaryTask.setPage(i);
				taskExecutor.submit(summaryTask);
			}
		} catch (Exception ex) {
			logger.error("An error occurred while handling task result.", ex);
		}
	}

	public void setTaskExecutor(CrawlerTaskExecutor taskExecutor) {
		this.taskExecutor = taskExecutor;
	}

}
